package cn.ycl.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kong.unirest.ContentType;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * @author YuanChangLiang
 * @description
 * @date created in 16:09 2021/10/8
 */


public class HttpUtil {

    /**
     * 获取ip对应地址地址
     * @param ip ip
     * @return
     */
    public static String getAddress(String ip){
        // 百度地图API
        String url = "http://api.map.baidu.com/location/ip?ip="+ ip +"&ak=N9jBGAGdHyxcbEmlog4q4hMawkYQR7cd";
        String body = postToBaidu(ip,url);
        JSONObject jsonObject = JSON.parseObject(body);
        String address = jsonObject.getJSONObject("content").getString("address");
        return unicodeToCn(address);

    }

    /**
     * 获取ip对应地址地址(比百度地图精准，还不用ak之类的秘钥)
     * @param ip ip
     * @return
     */
    public static String getAddressPlus(String ip){
        if(ip.contains("127.0.0.1") || ip.contains("0:0:0:0:0:0:0:1")){
            return "本地";
        }
        //更精确的地图API
        String url = "https://sp1.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query="+ ip +"&resource_id=5809";
        String body = postToBaidu(ip,url);
        JSONObject jsonObject = JSON.parseObject(body);
        JSONArray data1 = jsonObject.getJSONArray("data");
        JSONObject o = (JSONObject)data1.get(0);
        return o.getString("location");

    }

    /**
     * 请求百度API获取ip对应地址
     * @param ip ip
     * @return 结果
     */
    public static String postToBaidu(String ip,String url){
        if(null==ip){
            return null;
        }
        // 取得IP所在的省市区信息
        HttpResponse<String> stringHttpResponse = Unirest.post(url)
                .body(new byte[1])
                .charset(StandardCharsets.UTF_8)
                .contentType(ContentType.APPLICATION_JSON.getMimeType())
                .asString();
        return stringHttpResponse.getBody();
    }


    /**
     * unicode转中文
     * @param unicode unicode编码数据
     * @return 中文
     */
    private static String unicodeToCn(String unicode) {
        String[] strs = unicode.split("\\\\u");
        StringBuilder returnStr = new StringBuilder();
        for (int i = 1; i < strs.length; i++) {
            returnStr.append((char) Integer.valueOf(strs[i], 16).intValue());
        }
        return returnStr.toString();
    }

    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

}
